import { ACCESS_TOKEN } from "@/utils/storage/key";
import router from ".";
import { useMenuStore } from "@/store/menu";
import { useUserStore } from "@/store/user";

router.beforeEach(async (to, _from, next) => {
  const menuStore = useMenuStore();
  const userStore = useUserStore();
  // 是否路由白名单
  if (!to.fullPath.startsWith("/white-path")) {
    // 是否登录授权
    if (localStorage.getItem(ACCESS_TOKEN)) {
      // 是否已经获取菜单权限
      if (!menuStore.menus.length) {
        // 查询用户信息
        await userStore.getUserInfo();
        // 查询用户角色信息-异步
        userStore.getRoleList();
        // 查询用户组织信息-异步
        userStore.getOrgList();
        // 查询菜单信息
        const { result } = await menuStore.getMenuTree();
        router.options.routes = router.getRoutes();
        if (result?.length) {
          next({ ...to, replace: true });
        } else {
          const [path] = to.fullPath.split("?");
          // vue-router内部进行了 encodeURIComponent
          next({
            path: "/white-path/login",
            query: { path },
          });
        }
        return;
      } else {
        next();
      }
    } else {
      const [path] = to.fullPath.split("?");
      // vue-router内部进行了 encodeURIComponent
      next({
        path: "/white-path/login",
        query: { path },
      });
    }
  } else {
    next();
  }
});

export default router;
